<?php

namespace App\Service\ChatGroup;

use App\Enums\WorkOrder\OrderEnum;
use App\Imports\Fy\FyRegionImport;
use App\Models\Appraise\AppraiseModel;
use App\Models\ChatGroup\ChatGroupFAQModel;
use App\Service\BaseService;
use App\Service\WorkOrder\ProblemFeedbackService;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Facades\Excel;

class ChatGroupFAQService
{

    /**
     * 问题排序列表
     *
     * @param int $level
     * @param int $pid
     * @return Builder[]|Collection
     */
    public static function faqSortList(int $level = 1, int $pid = 0)
    {
        $list = ChatGroupFAQModel::query()
                                 ->where('level', $level)
                                 ->when($level > 1, function ($query) use ($pid) {
                                     $query->where('pid', $pid);
                                 })
                                 ->select(['id', 'desc'])
                                 ->orderBy('sort')
                                 ->orderByDesc('sortDateTimestamp')
                                 ->get();

        return $list;
    }

    /**
     * 更新排序
     *
     * @param int $id
     * @param int $sort
     * @return void
     * @throws Exception
     */
    public static function faqUpdateSort(int $id, int $sort)
    {
        $model = ChatGroupFAQModel::query()->where('id', $id)->first();
        if (!$model) {
            throw new Exception('不存在的数据');
        }

        if ($model->sort >= $sort) {
            $model->sortDateTimestamp = time();
        } else {
            $model->sortDateTimestamp = 0;
        }

        $model->sort = $sort;
        $model->save();

//        dispatch(function () {
        ChatGroupFAQService::faqRefreshUpdateSort();
//        });
    }


    /**
     * FAQ 更新
     *
     * @param int $id
     * @param string $parentTitle
     * @param string $parentParentTitle
     * @param string $desc
     * @param string $indexNumber
     * @param string $description
     * @param string $answer
     * @param array $images
     * @param array $videos
     * @return void
     */
    public static function faqUpdate(
        int $id,
        string $parentTitle,
        string $parentParentTitle,
        string $desc,
        string $indexNumber,
        string $description,
        string $answer,
        array $images,
        array $videos
    ) {
        $faqModel = ChatGroupFAQModel::query()
                                     ->where('id', $id)
                                     ->first();

        $faqModelOrg = clone $faqModel;
        $faqModelOrg->getParentRel;
        if (empty($faqModel)) {
            BaseService::throwErr("不存在");
        }

        // 名称校验
        if (ChatGroupFAQService::checkAllDescExist($parentParentTitle, $parentTitle, $desc, $faqModel)) {
            BaseService::throwErr("该名称已存在");
        }

        // 呼博特编号校验
        if (ChatGroupFAQService::checkIndexNumExist($faqModel, $indexNumber)) {
            BaseService::throwErr("呼博特编号重复了");
        }

        // 更新数据
        // 处理一级名称
        $parentParentModel = ChatGroupFAQService::getOrInsert([
            'desc'  => $parentParentTitle,
            'level' => 1,
            'pid'   => 0
        ]);

        // 处理二级名称
        $parentModel = ChatGroupFAQService::getOrInsert([
            'desc'  => $parentTitle,
            'level' => 2,
            'pid'   => $parentParentModel->id
        ]);

        // 处理三级
        $faqModel->desc        = $desc;
        $faqModel->pid         = $parentModel->id;
        $faqModel->indexNumber = $indexNumber;
        $faqModel->description = $description;
        $faqModel->updatedAt   = time();
        $faqModel->answer      = $answer;

        $attachment = [];
        if (!empty($images)) {

            $attachment[] = [
                'url'  => $images,
                'type' => 'images'
            ];
        }
        if (!empty($videos)) {
            $attachment[] = [
                'url'  => $videos,
                'type' => 'videos'
            ];
        }

        $faqModel->attachment = json_encode($attachment);
        $faqModel->save();

        // 校验更新后数据还是否存在
        $pCount = ChatGroupFAQModel::query()->where('pid', $faqModelOrg->pid)->count();
        if (!$pCount) {
            ChatGroupFAQModel::query()->where('id', $faqModelOrg->pid)->delete();
            $faqModel->sortDateTimestamp = 0;
            $faqModel->save();
        }

        $ppCount = ChatGroupFAQModel::query()->where('pid', $faqModelOrg->getParentRel->pid)->count();
        if (!$ppCount) {
            ChatGroupFAQModel::query()->where('id', $faqModelOrg->getParentRel->pid)->delete();
        }

        dispatch(function () {
            ChatGroupFAQService::faqRefreshUpdateSort();
        });
    }

    /**
     * 详情
     *
     * @param int $id
     * @return array
     * @throws Exception
     */
    public static function info(int $id): array
    {
        $model = ChatGroupFAQModel::query()
                                  ->where('id', $id)
                                  ->first();

        if (empty($model)) {
            BaseService::throwErr("不存在");
        }

        $parentInfo       = $model->getParentRel;
        $parentParentInfo = $parentInfo->getParentRel;

        $images = [];
        $videos = [];

        if (!empty($model->attachment)) {
            $attachment = json_decode($model->attachment, 1);
            $typeBy     = array_column($attachment, null, 'type');
            $images     = $typeBy['images']['url'] ?? [];
            $videos     = $typeBy['videos']['url'] ?? [];
        }

        return [
            'id'                => $model->id,
            'indexNumber'       => $model->indexNumber,
            'sortNumber'        => vsprintf('%s.%s.%s',
                [$parentParentInfo->sort, $parentInfo->sort, $model->sort ?? '']),
            'parentParentTitle' => $parentParentInfo->desc ?? '',
            'parentTitle'       => $parentInfo->desc ?? '',
            'desc'              => $model->desc,
            'description'       => $model->description,
            'answer'            => $model->answer,
            'images'            => $images,
            'videos'            => $videos
        ];
    }


    /**
     * 问题列表展示
     *
     * @param int $pageSize
     * @param int $pageNum
     * @param string $titleName
     * @return array
     */
    public static function getFAQLevel3List(int $pageSize, int $pageNum, string $titleName = ''): array
    {
        $categoryList = ChatGroupFAQModel::query()
                                         ->where('level', '<', 3)
                                         ->get();

        $categoryLevel1 = $categoryList->where('level', 1)
                                       ->keyBy('id')
                                       ->toArray();

        $categoryLevel2 = $categoryList->where('level', 2)
                                       ->keyBy('id')
                                       ->toArray();

        foreach ($categoryLevel2 as &$level2Item) {
            $level2Item['parentName'] = $categoryLevel1[$level2Item['pid']]['desc'] ?? '';
            $level2Item['parentSort'] = $categoryLevel1[$level2Item['pid']]['sort'] ?? '';
        }

        $pidAll = [];
        if (!empty($titleName)) {
            $filterListOne = $categoryList->where('level', 1)
                                          ->filter(function ($item) use ($titleName) {
                                              if (strpos($item->desc, $titleName) !== false) {
                                                  return true;
                                              }
                                              return false;
                                          });

            $filterListTwo = $categoryList->where('level', 2)
                                          ->filter(function ($item) use ($titleName) {
                                              if (strpos($item->desc, $titleName) !== false) {
                                                  return true;
                                              }
                                              return false;
                                          });

            $parentId = $filterListTwo->pluck('id');

            $parentParentId = $filterListOne->pluck('id');

            $parentParentChild = ChatGroupFAQModel::query()
                                                  ->whereIn('pid', $parentParentId)
                                                  ->get()
                                                  ->pluck('id');

            $pidAll = $parentId->merge($parentParentChild)->toArray();
        }

        $list = ChatGroupFAQModel::query()
                                 ->when(!empty($titleName), function ($query) use ($pidAll, $titleName) {
                                     $query->whereIn('pid', $pidAll)
                                           ->orWhere('desc', 'like', '%' . $titleName . '%');
                                 })
                                 ->where('level', 3)
                                 ->orderBy('sortScore')
                                 ->paginate($pageSize, ['*'], 'pageNum', $pageNum);


        return BaseService::pageLists($list, function ($item) use ($categoryLevel2) {
            return [
                'id'          => $item->id,
                'indexNumber' => $item->indexNumber,
                'sortNumber'  => vsprintf('%s.%s.%s', [
                    $categoryLevel2[$item->pid]['parentSort'] ?? '.',
                    $categoryLevel2[$item->pid]['sort'] ?? '.',
                    $item->sort ?? ''
                ]),
                'title'       => vsprintf('%s-%s-%s', [
                    $categoryLevel2[$item->pid]['parentName'] ?? '-',
                    $categoryLevel2[$item->pid]['desc'] ?? '-',
                    $item->desc ?? '-'
                ]),
                'answerType'  => (function ($item) {
                    $returnStr = '';
                    if (!empty($item->answer)) {
                        $returnStr .= '文字、';
                    }

                    if (empty($item->attachment)) {
                        return trim($returnStr, '、');
                    }

                    $list = json_decode($item->attachment, 1);
                    if (empty($list)) {
                        return trim($returnStr, '、');
                    }

                    $typeBy = array_column($list, 'type');

                    if (in_array('images', $typeBy)) {
                        $returnStr .= '图片、';
                    }
                    if (in_array('videos', $typeBy)) {
                        $returnStr .= '视频';
                    }
                    return trim($returnStr, '、');
                })($item),
                'linkType'    => (function ($item) {
                    $returnStr = '';
                    if (empty($item->answer)) {
                        return '';
                    }
                    if (strpos($item->answer, 'feedback') !== false) {
                        $returnStr .= '工单链接、';
                    }

                    if (strpos($item->answer, 'function-activation') !== false) {
                        $returnStr .= '功能开通';
                    }

                    return trim($returnStr, '、');

                })($item),
                'description' => $item->description,
                'sort'        => $item->sort,
                'usefulNum'   => $item->usefulNum,
                'uselessNum'  => $item->uselessNum,
            ];
        });
    }


    /**
     * 删除常见问题
     *
     * @param int $id
     * @return void
     */
    public static function del(int $id)
    {
        $info = ChatGroupFAQModel::query()->where('id', $id)->with('getParentRel')->first();
//
        $pid  = $info->pid;
        $ppid = $info->getParentRel->pid;
        $info->delete();

        // 校验更新后数据还是否存在
        $pCount = ChatGroupFAQModel::query()->where('pid', $pid)->count();

        if (!$pCount) {
            ChatGroupFAQModel::query()->where('id', $pid)->delete();
        }

        $ppCount = ChatGroupFAQModel::query()->where('pid', $ppid)->count();
        if (!$ppCount) {
            ChatGroupFAQModel::query()->where('id', $ppid)->delete();
        }

        return;
    }

    /**
     * 校验名称是否存在
     *
     * @param string $parentTitle
     * @param string $parentParentTitle
     * @param string $desc
     * @param Model|null $faqModel
     * @return bool
     */
    public static function checkAllDescExist(
        string $parentTitle,
        string $parentParentTitle,
        string $desc,
        ?Model $faqModel
    ): bool {
        // 校验一级是否存在
        $isExistOne = ChatGroupFAQService::getDescByDesc($parentTitle, 0, 1);
        // 校验二级
        $isExistTwo = false;

        if (!empty($isExistOne)) {
            $isExistTwo = ChatGroupFAQService::getDescByDesc($parentParentTitle, $isExistOne->id, 2);
        }
        // 校验三级
        $isExistThree = false;
        if (!empty($isExistTwo)) {
            $isExistThree = ChatGroupFAQService::getDescByDesc($desc, $isExistTwo->id, 3, $faqModel->id ?? 0);
        }

        if (!empty($isExistThree)) {
            return true;
        }

        return false;
    }

    /**
     * 校验编号是否存在
     *
     * @param Model $faqModel
     * @param string $indexNumber
     * @return bool
     */
    public static function checkIndexNumExist(?Model $faqModel, string $indexNumber): bool
    {
        return ChatGroupFAQModel::query()
                                ->where('indexNumber', $indexNumber)
                                ->when(!empty($faqModel), function ($query) use ($faqModel) {
                                    $query->where('id', '<>', $faqModel->id);
                                })
                                ->exists();
    }

    /**
     * 创建 一二级分类
     *
     * @param string $desc
     * @param int $pid
     * @param int $level
     * @return ChatGroupFAQModel
     */
    public static function addDescByLevel(string $desc, int $pid, int $level): ChatGroupFAQModel
    {
        $maxSort = ChatGroupFAQModel::query()->where('level', $level)->max('sort');

        $model                    = new ChatGroupFAQModel();
        $model->desc              = $desc;
        $model->level             = $level;
        $model->pid               = $pid;
        $model->sort              = ++$maxSort;
        $model->sortDateTimestamp = time();
        $model->save();

        ChatGroupFAQService::faqRefreshUpdateSortByPid($pid);
        return $model;
    }


    /**
     * 获取对应分类
     *
     * @param string $desc
     * @param int $pid
     * @param int $level
     * @param int $id
     * @return Builder|Model|object|null
     */
    public static function getDescByDesc(string $desc, int $pid, int $level, int $id = 0)
    {
        // 校验一级是否存在
        return ChatGroupFAQModel::query()
                                ->where('desc', $desc)
                                ->where('pid', $pid)
                                ->where('level', $level)
                                ->when($id > 0, function ($query) use ($id) {
                                    $query->where('id', '<>', $id);
                                })
                                ->first();
    }

    /**
     * 获取数据 或者创建
     *
     * @param array $condition
     * @param array $data
     * @return Builder|Model
     */
    public static function getOrInsert(array $condition, array $data = [])
    {
        if (empty($condition['level'])) {
            BaseService::throwErr("level 不能为空");
        }
        if (empty($condition['desc'])) {
            BaseService::throwErr("desc 不能为空");
        }

        return ChatGroupFAQModel::query()
                                ->where($condition)
                                ->firstOr(['*'], function () use ($condition, $data) {
                                    $pid     = $condition['pid'] ?? 0;
                                    $desc    = $condition['desc'] ?? '';
                                    $maxSort = ChatGroupFAQModel::query()
                                                                ->where('level', $condition['level'])
                                                                ->where('pid', $pid)
                                                                ->max('sort');

                                    $model                    = new ChatGroupFAQModel();
                                    $model->desc              = $desc;
                                    $model->level             = $condition['level'];
                                    $model->pid               = $pid;
                                    $model->sort              = ++$maxSort;
                                    $model->sortDateTimestamp = 0;
                                    $model->save();

                                    ChatGroupFAQService::faqRefreshUpdateSortByPid($pid);
                                    return $model;
                                });
    }

    /**
     * 单独更新排序
     *
     * @param int $pid
     * @return void
     */
    public static function faqRefreshUpdateSortByPid(int $pid = 0)
    {
        // 更新排序
        $level1 = ChatGroupFAQModel::query()
                                   ->where('pid', $pid)
                                   ->orderBy('sort')
                                   ->orderByDesc('sortDateTimestamp')
                                   ->get();

        $level1Time = 1;
        foreach ($level1 as $level1Item) {
            $level1Item->sort = $level1Time;
            $level1Item->save();
            ++$level1Time;
        }
    }

    public static function fileCheckAndImport($file, bool $isImport): array
    {
        $importResult = false;
        $errorMsg     = [];
        $import       = Excel::toCollection((object)null, $file);

        $data = $import->toArray();

        $data = $data[0]; // sheet1

        if (!count($data)) {
            $errorMsg[] = '请上传模版内的完整内容';
            return [$errorMsg, $importResult];
        }

        $headerData  = array_filter($data[0]);
        $headerCheck = ChatGroupFAQService::checkFileHeader($headerData);
        if ($headerCheck) {
            $errorMsg[] = $headerCheck;
            return [$errorMsg, $importResult];
        }

        // 校验内容
        unset($data[0]);

        // 过滤空数据
        foreach ($data as &$datum) {
            $datum = array_filter($datum);
        }
        $data = array_filter($data);

        // 校验表格中的内容是否缺失或者多余
        foreach ($data as $key => $name) {
            if (
                empty($name[0]) ||
                empty($name[1]) ||
                empty($name[2])
            ) {
                if (count($name) != 6) {
                    $errorMsg[] = "第{$key}行: 文档内数据缺失";
                }
            }

            if (empty($name[5])) {
                $errorMsg[] = "第{$key}行: 呼波特编号为空,请补充";
            }
        }

        if (count($errorMsg)) {
            return [$errorMsg, $importResult];
        }

        // 校验表格中的节点名称是否重复
        $tmpNameArr = [];
        // 过滤空数据
        foreach ($data as $key => $name) {
            $tmpNameArr[$key + 1] = $name[0] . '_' . $name[1] . '_' . $name[2];
        }

        $tmpNameArrAvert  = array_flip($tmpNameArr);
        $tmpNameArrCounts = array_count_values($tmpNameArr);

        foreach ($tmpNameArrCounts as $value => $count) {
            if ($count > 1) {
                $errorMsg[] = "第{$tmpNameArrAvert[$value]}行: 文档内名称({$value})重复{$count}次";
            }
        }
        if (count($errorMsg)) {
            return [$errorMsg, $importResult];
        }

        // 校验表格中的节点名称是否重复
        $tmpNameArr = [];

        // 过滤空数据
        foreach ($data as $key => $name) {
            $tmpNameArr[$key + 1] = $name[5];
        }

        $tmpNameArrAvert  = array_flip($tmpNameArr);
        $tmpNameArrCounts = array_count_values($tmpNameArr);

        foreach ($tmpNameArrCounts as $value => $count) {
            if ($count > 1) {
                $errorMsg[] = "第{$tmpNameArrAvert[$value]}行: 文档内呼博特编号({$value})重复{$count}次";
            }
        }
        if (count($errorMsg)) {
            return [$errorMsg, $importResult];
        }


        // 校验表格中的呼博特的编号是否重复
        $data      = array_filter($data);
        $allDbData = ChatGroupFAQService::getAllFaq();

        $filterOutId = [];
        $overWrite   = 0;
        $newWrite    = 0;
        foreach ($data as $key => $faqData) {
            // 判断三级类目是否存在
            $one = $allDbData
                ->where('parentParentDesc', $faqData[0])
                ->where('parentDesc', $faqData[1])
                ->where('desc', $faqData[2])
                ->first();

            if (!empty($one)) {
                $filterOutId[] = $one['id'];
                $overWrite++;
            } else {
                $newWrite++;
            }
        }


        // 获取所有数据
        $indexNumberList = array_filter(array_column($data, 5));

        $existIndexNumberList = ChatGroupFAQModel::query()
                                                 ->whereIn('indexNumber', $indexNumberList)
                                                 ->where('level', 3)
                                                 ->whereNotIn('id', $filterOutId)
                                                 ->get()
                                                 ->keyBy('indexNumber');

        foreach ($existIndexNumberList as $existList) {
            $errorMsg[] = "呼博特编号 {$existList['indexNumber']} 重复,请修正";
        }

        if (count($errorMsg)) {
            return [$errorMsg, $importResult];
        }

        $errorMsg        = [];
        $loopTimes       = 1000;
        $urlList         = ChatGroupFAQModel::getSendWorkOrder();
        $lastLinkUrlList = [];

        foreach ($urlList as $value) {
            if (is_array($value['child'])) {
                foreach ($value['child'] as $c) {
                    if ($value['key'] != '功能开通') {
                        $prefix = '工单链接|';
                    } else {
                        $prefix = '功能跳转|';
                    }
                    $lastLinkUrlList[] = $c + [
                            'fullText' => $prefix . $value['key'] . '|' . $c['key']
                        ];
                }
            }
        }

        $lastLinkUrlList = array_column($lastLinkUrlList, null, 'fullText');

        if (!count($errorMsg) && $isImport) {

            foreach ($data as $key => $faqData) {
                ++$loopTimes;
                // 校验一二三级节点名称
                $titleOne    = $faqData[0];
                $titleTwo    = $faqData[1];
                $titleThree  = $faqData[2];
                $description = $faqData[3] ?? '';
                $answer      = $faqData[4] ?? '';
                $indexNumber = $faqData[5];

                // 更新数据
                // 处理一级名称
                $parentParentModel = ChatGroupFAQService::getOrInsert([
                    'desc'  => $titleOne,
                    'level' => 1,
                    'pid'   => 0
                ]);

                $parentModel = ChatGroupFAQService::getOrInsert([
                    'desc'  => $titleTwo,
                    'level' => 2,
                    'pid'   => $parentParentModel->id
                ]);

                $faqModel = ChatGroupFAQService::getOrInsert([
                    'desc'  => $titleThree,
                    'level' => 3,
                    'pid'   => $parentModel->id
                ]);


                $answer = (function ($answer, $lastLinkUrlList) {
                    $pattern = '/{{(.*?)}}/';

                    preg_match_all($pattern, $answer, $matches);

                    if (empty($matches[1])) {
                        return $answer;
                    }

                    // 输出所有匹配结果
                    foreach ($matches[1] as $match) {
                        // 不等于 3 的时候异常退出
                        if (empty($lastLinkUrlList[$match])) {
                            // TODO 不存在
                        } else {
                            $linkUrl    = $lastLinkUrlList[$match]['href'] ?? '';
                            $replaceStr = '[点击此处](' . $linkUrl . ')';
                            $answer     = str_replace('{{' . $match . '}}', $replaceStr, $answer);
                        }
                    }

                    return $answer;

                })($answer, $lastLinkUrlList);

                $faqModel->indexNumber       = $indexNumber;
                $faqModel->answer            = $answer;
                $faqModel->description       = $description;
                $faqModel->sortDateTimestamp = $loopTimes;
                $faqModel->save();
            }

            dispatch(function () {
                ChatGroupFAQService::faqRefreshUpdateSort();
            });

            $importResult = true;
        }
        $errorMsg[] = vsprintf('共%s条数据，%s条新增，%s条覆盖', [
            count($data),
            $newWrite,
            $overWrite
        ]);

        return [$errorMsg, $importResult];
    }

    /**
     * 校验表头内容
     *
     * @param array $header
     * @return string
     */
    public static function checkFileHeader(array $header): string
    {
        if (count($header) != 6) {
            return "请修正表头内容";
        }

        if (($header[0] ?? '') != "一级节点") {
            return "请修正表头'一级节点'的内容";
        }

        if (($header[1] ?? '') != "二级节点") {
            return "请修正表头'二级节点'的内容";
        }

        if (($header[2] ?? '') != "三级节点") {
            return "请修正表头'三级节点'的内容";
        }

        if (($header[3] ?? '') != "描述") {
            return "请修正表头'描述'的内容";
        }

        if (($header[4] ?? '') != "文字答案") {
            return "请修正表头'文字答案'的内容";
        }

        if (($header[5] ?? '') != "呼波特编号") {
            return "请修正表头'呼波特编号'的内容";
        }

        return '';
    }


    /**
     * 工单, 功能开通链接
     *
     * @param int $problemPid
     * @return array
     */
    public static function getFaqLinkUrl(int $problemPid = 0): array
    {
        $urlList = ChatGroupFAQModel::getSendWorkOrder();

        $resultLinkList = [];
        switch ($problemPid) {
            // 功能开通
            case OrderEnum::PROBLEM_PID_5:
                $resultLinkList = [$urlList[4]];
                break;
            default:
                unset($urlList[4]);

                $resultLinkList = $resultLinkList + $urlList;
                break;
        }
        return array_values($resultLinkList);
    }

    /**
     * 全量刷新排序
     *
     * @return void
     */
    public static function faqRefreshUpdateSort()
    {
        // 排序 1 排序
        $level1 = ChatGroupFAQModel::query()
                                   ->where('level', 1)
                                   ->orderBy('sort')
                                   ->orderByDesc('sortDateTimestamp')
                                   ->get();

        $level1Time = 1;
        foreach ($level1 as $level1Item) {
            $level1Item->sort              = $level1Time;
            $level1Item->sortDateTimestamp = $level1Time;
            $level1Item->save();
            ++$level1Time;
        }

        // 排序 2 排序
        $level1 = ChatGroupFAQModel::query()
                                   ->where('level', 1)
                                   ->orderByDesc('sortDateTimestamp')
                                   ->get();


        foreach ($level1 as $level1Item) {
            $level2     = ChatGroupFAQModel::query()
                                           ->where('pid', $level1Item->id)
                                           ->orderBy('sort')
                                           ->orderByDesc('sortDateTimestamp')
                                           ->get();
            $level2Time = 1;
            foreach ($level2 as $level2Item) {
                $level2Item->sort              = $level2Time;
                $level2Item->sortDateTimestamp = $level2Time;
                $level2Item->save();
                ++$level2Time;
            }
        }


        // 排序 3 排序
        $level2 = ChatGroupFAQModel::query()
                                   ->where('level', 2)
                                   ->orderByDesc('sortDateTimestamp')
                                   ->get();

        foreach ($level2 as $level2Item) {
            $level3 = ChatGroupFAQModel::query()
                                       ->where('pid', $level2Item->id)
                                       ->orderBy('sort')
                                       ->orderByDesc('sortDateTimestamp')
                                       ->get();

            $level3Time = 1;
            foreach ($level3 as $level3Item) {

                $p  = $level3Item->getParentRel;
                $pp = $p->getParentRel;

                $level3Item->sort              = $level3Time;
                $level3Item->sortDateTimestamp = $level3Time;
                $level3Item->sortScore         = $pp->sort * ChatGroupFAQModel::LEVEL_ZERO_SCORE + $p->sort * ChatGroupFAQModel::LEVEL_ONE_SCORE + $level3Item->sort * ChatGroupFAQModel::LEVEL_TWO_SCORE;
                $level3Item->save();
                ++$level3Time;
            }
        }
    }

    /**
     * 返回数据库中的数据
     *
     * @return \Illuminate\Support\Collection
     */
    public static function getAllFaq(): \Illuminate\Support\Collection
    {
        $list = ChatGroupFAQModel::query()->get()->keyBy('id');

        $one = $list->where('level', 1)->toArray();

        $two = $list->where('level', 2)->toArray();

        $three = $list->where('level', 3)->toArray();

        foreach ($three as &$threeValue) {
            $threeValue['parent']     = $two[$threeValue['pid']] ?? [];
            $threeValue['parentDesc'] = $two[$threeValue['pid']]['desc'] ?? '';

        }
        unset($threeValue);

        foreach ($three as &$threeValue) {
            $threeValue['parent']['parent'] = $one[$threeValue['parent']['pid']] ?? [];
            $threeValue['parentParentDesc'] = $one[$threeValue['parent']['pid']]['desc'] ?? '';

        }
        return collect(array_values($three));
    }
}
